﻿using Dispatcher.Tasks.Models;
using MiniFox.Net.Http;

namespace Dispatcher.Tasks
{
    public static class QueueFactory
    {
        static readonly Dictionary<string, Queue<QueueItem>> _queueDictionary;
        static bool _initialized;

        static QueueFactory()
        {
            _queueDictionary = new Dictionary<string, Queue<QueueItem>>();
            _initialized = false;
        }

        internal static void InitQueueGroups(IEnumerable<QueueItem> queueItems)
        {
            if (_initialized)
                return;
            var groups = queueItems.GroupBy(q => q.QueueName);
            foreach (var group in groups)
            {
                var queue = new Queue<QueueItem>();
                foreach(var item in group)
                {
                    queue.Enqueue(item);
                }
                _queueDictionary.Add(group.Key, queue);
            }

            _initialized = true;
        }

        public static string[] LoadGroup()
        {
            return _queueDictionary.Select(q => q.Key).ToArray();
        }

        public static QueueItem[] LoadQueue()
        {
            return _queueDictionary.SelectMany(q => q.Value).ToArray();
        }

        public static Queue<QueueItem> LoadQueue(string name)
        {
            if (!_queueDictionary.ContainsKey(name))
            {
                _queueDictionary.Add(name, new Queue<QueueItem>());
            }
            return _queueDictionary[name];
        }

        internal static HttpAdapter CreateAdapter(string adapterName)
        {
            var httpAdapter = MiniFox.Net.WebAdapterFactory.GetHttpAdapterByName(adapterName);
            return httpAdapter;
        }

        public static QueueItem CreateQueueItem(string queueName, string executionId, HttpService httpService)
        {
            return new QueueItem(queueName, executionId, httpService);
        }

        public static QueueItem CreateQueueItem(string queueName, string executionId, string webAdapterName, string serviceName)
        {
            var webAdapter = CreateAdapter(webAdapterName);
            var httpService = webAdapter.GetService(serviceName);
            return CreateQueueItem(queueName, executionId, httpService);
        }

    }
}
